import { useRef, useState, useEffect } from "react";
import { useRouter } from 'next/router'
import classNames from "classnames";

export default function Register(props) {

    const router = useRouter()

    const emailRef = useRef(null);
    const captchaRef = useRef(null);
    const usernameRef = useRef(null);
    const passwordRef = useRef(null);

    const [clock, setClock] = useState(0);

    // valid message has 3 state: blank:0, valid:1, invalid:2
    const [isEmailValid, setIsEmailValid] = useState(0);
    const [isCaptchaValid, setIsCaptchaValid] = useState(0);
    const [isUsernameValid, setIsUsernameValid] = useState(0);
    const [isPasswordValid, setIsPasswordValid] = useState(0);


    let emailClasses = classNames('form-control', {
        'is-valid': isEmailValid === 1,
        'is-invalid': isEmailValid === 2,
    });
    let captchaClasses = classNames('form-control', {
        'is-valid': isCaptchaValid === 1,
    });
    let usernameClasses = classNames('form-control', {
        'is-valid': isUsernameValid === 1,
        'is-invalid': isUsernameValid === 2,
    });
    let passwordClasses = classNames('form-control', {
        'is-valid': isPasswordValid === 1,
        'is-invalid': isPasswordValid === 2,
    });


    function validateEmail(e) {
        e.preventDefault();
        const regexEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if (emailRef.current.value.match(regexEmail)) {
            setIsEmailValid(1);
        } else {
            setIsEmailValid(2);
        }
    }

    function validateCaptcha(e) {
        e.preventDefault();
        if (captchaRef.current.value.length === 4) {
            setIsCaptchaValid(1);
        }
    }

    function validateUsername(e) {
        e.preventDefault();
        if (usernameRef.current.value.length >= 4 && usernameRef.current.value.length <= 15) {
            setIsUsernameValid(1);
        } else {
            setIsUsernameValid(2);
        }
    }

    function validatePassword(e) {
        e.preventDefault();
        const regexPassword = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$).{8,20}$/;

        if (passwordRef.current.value.match(regexPassword)) {
            setIsPasswordValid(1);
        } else {
            setIsPasswordValid(2);
        }
    }


    // 60s后重发
    useEffect(() => {
        if (clock > 0) {
            setTimeout(() => {
                setClock(clock - 1)
            }, 1000);
        }
    }, [clock]);

    
    function handleCaptchaButton(e) {
        e.preventDefault();
        const regexEmail = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
        if (emailRef.current.value.match(regexEmail)) {
            setClock(60);
        } else {
            setIsEmailValid(2);
        }
    }

    function handleRegister(e) {
        e.preventDefault();
        if (isEmailValid === 1 && isCaptchaValid === 1 && isUsernameValid === 1 && isPasswordValid === 1) {
            router.push('/');
        }
    }


    return (
        <div className="d-flex justify-content-center mt-5" >
            <form className="col-md-4">
                <div className="mb-3">
                    <label className="form-label">注册邮箱</label>
                    <input type="email" className={emailClasses} ref={emailRef} onInput={validateEmail} placeholder="请填写邮箱" required />
                    <div className="invalid-feedback">
                        邮箱格式不正确
                    </div>
                </div>
                <div className="mb-3">
                    <label className="form-label">验证码</label>
                    <div className="input-group">
                        <input type="text" className={captchaClasses} onInput={validateCaptcha} ref={captchaRef} placeholder="请填写四位验证码" required />
                        <button className="btn btn-outline-secondary is-valid" type="button" onClick={handleCaptchaButton} disabled={clock > 0}>{clock === 0 ? '发送验证码到邮箱' : `${clock}S后重发`}</button>
                    </div>
                </div>
                <div className="mb-3">
                    <label className="form-label">昵称 <span className="small text-muted">长度4-15</span></label>
                    <input type="text" className={usernameClasses} ref={usernameRef} onInput={validateUsername} placeholder="请填写昵称" required />
                    <div className="invalid-feedback">
                        用户名格式不正确
                    </div>
                </div>
                <div className="mb-3">
                    <label className="form-label">密码 <span className="small text-muted">包含数字,英文,字符中的两种以上,长度8-20</span></label>
                    <input type="password" className={passwordClasses} ref={passwordRef} onInput={validatePassword} placeholder="请填写密码" required />
                    <div className="invalid-feedback">
                        包含数字,英文,字符中的两种以上,长度8-20
                    </div>
                </div>
                <button type="submit" className="btn btn-primary" onClick={handleRegister}>注册</button>
            </form>
        </div>
    )
};
